WebSocket : Websocket server and client
The websocket
module includes client and server functions, which are provided via WsClient
and WsServer
respectively. Once the connection is established, the APIs used to send and receive messages are similar whether you are acting as a client or a server.
User can use the following code to import the websocket
module.
var websocket = require('websocket');
Support
The following shows websocket
module APIs available for each permissions.
User Mode | Privilege Mode | |
---|---|---|
websocket.createServer | ● | ● |
wsServer.start | ● | ● |
wsServer.stop | ● | ● |
wsServer.port | ● | ● |
wsServer.broadcast | ● | ● |
wsServerChannel.send | ● | ● |
wsServerChannel.close | ● | ● |
websocket.createClient | ● | ● |
wsClient.close | ● | ● |
wsClient.ping | ● | ● |
wsClient.send | ● | ● |
WsServer Class
websocket.createServer(path[, saddr[, tlsOpt]])
path
{String} The uri path of websocket server.saddr
{HttpServer | WebApp | Object} it can be:- Server socket address, the server listen it self's port. If the port of
saddr
is set to 0, the setting port will be assigned automatically, and the port can be found throughwsServer.port()
. HttpServer
object, the http protocol upgrade to websocket protocol. In this mode, the websocket does not listen it self's port, thetlsOpt
is invalid.WebApp
object, the same toHttpServer
.
- Server socket address, the server listen it self's port. If the port of
tlsOpt
{Object} TLS securely connections options. default: undefined, means use TCP connection.
This method creates websocket server.
Example
var wsServer = Websocket.createServer('/', saddr);
UPGRADE mode
In UPGRADE mode, the websocket server is created from http server or webapp. The websocket server does not need to directly listen for client connections. When the http protocol initiates an upgrade of the websocket protocol request, the request is dispatched to the websocket server. In UPGRADE mode, websocket should not call start()
.
Create websocket server in UPGRADE mode:
var HttpServer = require('http').HttpServer;
var WsServer = require('websocket').WsServer;
var socket = require('socket');
var saddr = socket.sockaddr(socket.INADDR_ANY, 8000);
var httpSer = HttpServer.createServer('./ws_from_http', handle, 0, saddr);
var wsServer = WsServer.createServer('/', httpSer);
...
httpSer.start();
WsServer Object
wsServer.start()
- Returns: {Boolean} Server start success or not.
Start websocket server.
Example
var wsServer = Websocket.createServer('/', saddr);
...
wsServer.start();
wsServer.stop()
Stop websocket server.
wsServer.port()
- Returns: {Integer | Undefined} Server socket port.
When the server starts with the MASTER
module, wsServer.port()
gets the port of the server, otherwise it returns undefined
.
Example
var port = wsServer.port();
console.log(port);
wsServer.broadcast(chunk)
chunk
{String | Buffer | Number | Boolean | Object} Data tobe broadcast.
Broadcast data to all websocket clients.
WsServer Events
start
Emitted when the websocket server start done.
stop
Emitted when the websocket server stop.
connection
Emitted when a client connect to server. It has the following properties:
channel
{WsServerChannel} The client connection object.
WsServerChannel Object
The WsServerChannel object is the connection object of the client. The user does not need to create it. It is passed as a parameter to the user callback function in the connection event.
channel.path
- {String}
Request url.
channel.headers
- {Array}
Request headers.
channel.eos
- {Object}
EdgerOS account and connection information. See eos middleware for details.
channel.send(chunk)
chunk
{String | Buffer | Number | Boolean | Object} Data tobe send to client.- Returns: {Boolean}
true
: success.false
: fail.
Send data to client.
channel.close([code[, reason]])
code
{Integer} The error code.reason
{String} The close reason.
Close the connection with server. When the connection is closed normally, the server will send an error code to the client.
Example
channel.close(1000);
WsServerChannel Events
close
A close
event is emitted when the client disconnected.
message
When data is received from the server a message
event is emitted with a msg
:
msg
{String | Buffer}
Example
channel.on('message', function(msg) {
console.log(msg.toString());
});
ping
This event is generated when the client ping packet is received, and the server automatically replies to the pong packet.
WsClient Class
websocket.createClient(url[, options[, tlsOpt]])
url
{String} Websocket url.options
{Object} Has the following properties:saddr
{Object} Server socket address. default: Use url parameter resolution, if you request the same domain name multiple times, it is recommended to set this parameter after manual domain name resolution to speed up the request.domain
{socket.AF_INET | socket.AF_INET6} If theurl
host is provided as a domain name, the domain name is resolved to an ipv4 or ipv6 address based on the domain.default: socket.AF_INET.path
{String} Socket path, if this path is not set, the client will use the path specified by theurl
.async
{Boolean} true - returnPromise
object; false - return client object,default: false.protocol
{String} One or more optional protocol strings, if there are more than one, use,
split. EdgerOS 1.5.5 and later versions support.
tlsOpt
{Object} TLS securely connections options. default: undefined, means use TCP connection.- Returns: {WebsocketClient | Promise} The websocket client object or promise object.depend on
async
option.
This method create WsClient object and connect to server.
WsClient Object
wsClient.close([code[, reason]])
code
{Integer} The error code.reason
{String} The close reason.
Close the connection with client. When the connection is closed normally, the client will send an error code to the server.
wsClient.ping([timeout[, callback]])
timeout
{Integer} Wait timeout in milliseconds. default: 30 seconds.callback
{Function} Pong response callback.pongTag
{String} Pong tag.
- Returns: {String} Ping tag.
When the client sends a ping message with tag, the server will reply with a pong message, and the pong message will carry the tag of the ping message. The client will verify the tag to determine whether it is an error. Ping-pong message keep connection alive.
The client will close the connection after sending the ping message if the corresponding pong message is not received during timeout.
wsClient.send(chunk)
chunk
{String | Buffer | Number | Boolean | Object} Data to be send to client.- Returns: {Boolean}
true
: success.false
: fail.
Send data to server.
WebsocketClient Events
open
Emitted when the client successfully connects to a websocket server.
close
A close
event is emitted when the client disconnected.
message
When data is received from the server a message
event is emitted with a msg
:
msg
{String | Buffer}
Example
Websocket server
- Create websocket server.
var socket = require('socket'); var WsServer = require('websocket').WsServer; var iosched = require('iosched'); var saddr = socket.sockaddr(socket.INADDR_ANY, 8000); var server = WsServer.createServer('/', saddr); server.on('connection', function (channel) { var info = `ws open channel: ${channel.id}.` console.log(info); channel.send(info); channel.on('message', function (msg) { console.log(`ws recv message, msg_type: ${typeof msg}`); var data = Buffer.isBuffer(msg) ? msg.toString() : msg; server.broadcast(data); }); channel.on('close', function () { console.log(`ws close channel:${channel.id}`); }); }); server.start(); while (true) { iosched.poll(); }
- Create websocket server from http server:
var HttpServer = require('http').HttpServer; var WsServer = require('websocket').WsServer; var iosched = require('iosched'); function handle(req, res) { res.end('This is websocket server, rejust http request.'); } var saddr = socket.sockaddr(socket.INADDR_ANY, 8000); var httpSer = HttpServer.createServer('./ws_from_http', handle, 0, saddr); var wsServer = WsServer.createServer('/', httpSer); wsServer.on('connection', function (channel) { var info = `ws open, server=${httpSer.groupName.name}, channel=${channel.id}.` console.log(info); channel.send(info); channel.on('message', function (msg) { console.log(`ws recv message, ${channel.id}`); wsServer.broadcast(msg); }); channel.on('close', function () { console.log(`ws close channel:${channel.id}`); }); }); httpSer.start(); while (true) { iosched.poll(); }
- Create websocket server from WebApp server:
var WebApp = require('webapp'); var WsServer = require('websocket').WsServer; var iosched = require('iosched'); var saddr = socket.sockaddr(socket.INADDR_ANY, 8000); var app = WebApp.create('./ws_from_web', 0, saddr); app.all('/', function(req, res) { res.end('This is websocket server, rejust http request.'); }); var wsServer = WsServer.createServer('/', app); wsServer.on('connection', function (channel) { var info = `ws open, server=${app.server.groupName.name}, channel=${channel.id}.` console.log(info); channel.send(info); channel.on('message', function (msg) { console.log(`ws recv message, ${channel.id}`); wsServer.broadcast(msg); }); channel.on('close', function () { console.log(` ws close channel:${channel.id}`); }); }); app.start(); while (true) { iosched.poll(); }
Websocket client
- Synchronization Example
var WsClient = require('websocket').WsClient; var iosched = require('iosched'); var count = 0; var timer = null; function loop(client) { console.log('client loop'); if (count < 100) { client.send(`client count: ${count++}`); } else { client.close(); } } var client = WsClient.createClient('ws://192.168.7.32:8000/'); if (client) { client.on('message', function (msg) { console.log('ws recv message:', msg); if (msg === 'close') { client.close(); } }); client.on('close', function () { console.log('ws close channel'); if (timer) { clearInterval(timer); timer = null; } }); client.on('open', function () { console.log('ws open channel'); timer = setInterval(loop, 2000, client); }); } while (true) { iosched.poll(); }
- Asynchronous Example
var WsClient = require('websocket').WsClient; var iosched = require('iosched'); var count = 0; var timer = null; function loop(client) { console.log('client loop'); if (count < 100) { client.send(`client count: ${count++}`); } else { client.close(); } } WsClient.createClient('ws://192.168.7.32:8000/', {async: true} ).then((client) => { client.on('message', function (msg) { console.log('ws recv message:', msg); if (msg === 'close') { client.close(); } }); client.on('close', function () { console.log('ws close channel'); if (timer) { clearInterval(timer); timer = null; } }); client.on('open', function () { console.log('ws open channel'); timer = setInterval(loop, 2000, client); }); }).catch((err) => { console.error(err.message); }); while (true) { iosched.poll(); }